<?php

namespace AuthMePE;

use pocketmine\plugin\PluginBase;
use pocketmine\Player;
use pocketmine\utils\Config;
use pocketmine\utils\TextFormat;
use pocketmine\scheduler\ServerScheduler;

use pocketmine\event\Listener;
use pocketmine\event\player\PlayerCommandPreprocessEvent;
use pocketmine\event\player\PlayerJoinEvent;
use pocketmine\event\player\PlayerMoveEvent;
use pocketmine\event\player\PlayerQuitEvent;
use pocketmine\event\entity\EntityDamageEvent;
use pocketmine\event\player\PlayerInteractEvent;
use pocketmine\event\inventory\InventoryPickupItemEvent;
use pocketmine\event\inventory\InventoryOpenEvent;
use pocketmine\event\block\BlockBreakEvent;
use pocketmine\event\block\BlockPlaceEvent;

use pocketmine\command\CommandSender;
use pocketmine\command\ConsoleCommandSender;
use pocketmine\command\Command;

use pocketmine\level\Level;
///use pocketmine\level\sound\BatSound;
//use pocketmine\level\sound\PopSound;
//use pocketmine\level\sound\LaunchSound;
use pocketmine\level\Position;
use pocketmine\math\Vector3;

use AuthMePE\Task;
use AuthMePE\Task2;
use AuthMePE\SessionTask;
use AuthMePE\SoundTask;
use AuthMePE\UnbanTask;
use AuthMePE\TokenDeleteTask;

use AuthMePE\BaseEvent;

use AuthMePE\PlayerAuthEvent;
use AuthMePE\PlayerLogoutEvent;
use AuthMePE\PlayerRegisterEvent;
use AuthMePE\PlayerUnregisterEvent;
use AuthMePE\PlayerChangePasswordEvent;
use AuthMePE\PlayerAddEmailEvent;
use AuthMePE\PlayerLoginTimeoutEvent;
use AuthMePE\PlayerAuthSessionStartEvent;
use AuthMePE\PlayerAuthSessionExpireEvent;

use specter\network\SpecterPlayer;

class AuthMePE extends PluginBase implements Listener{
	
	private static $instance = null;
	private $login = [];
	private $session = [];
	private $bans = [];
	
	private $token_generated = null;
	
	private $specter = false;
	
	const VERSION = "0.1.5";
	
	public function onEnable(){
		$sa = $this->getServer()->getPluginManager()->getPlugin("SimpleAuth");
		if($sa !== null){
			$this->getLogger()->notice("SimpleAuth已经被禁用，因为它是一个冲突插件");
			$this->getServer()->getPluginManager()->disablePlugin($this);
		}
		if(!is_dir($this->getDataFolder())){
		  mkdir($this->getDataFolder());
		}
		$this->saveDefaultConfig();
	  $this->cfg = $this->getConfig();
	  $this->reloadConfig();
		if(!is_dir($this->getDataFolder()."data")){
			mkdir($this->getDataFolder()."data");
		}
		$this->data = new Config($this->getDataFolder()."data/data.yml", Config::YAML, array());
		$this->ip = new Config($this->getDataFolder()."data/ip.yml", Config::YAML);
		$this->specter = false; //Force false
		self::$instance = $this;
		$sp = $this->getServer()->getPluginManager()->getPlugin("Specter");
		if($sp !== null){
			$this->getServer()->getLogger()->info("Loaded with Specter!");
			$this->specter = true;
		}
		$this->getServer()->getScheduler()->scheduleRepeatingTask(new Task($this), 20 * 3);
		$this->getServer()->getPluginManager()->registerEvents($this, $this);
		if($this->getServer()->getPluginManager()->isPluginEnabled($this) !== true){
		  $this->getLogger()->notice("服务器将因安全原因关闭，因为AuthMePE被禁用！");
		  $this->getServer()->shutdown();
		}
		$this->getLogger()->info(TextFormat::GREEN."加载成功！");
	}
	
	public static function getInstance(){
	  return self::$instance;
	}
	
	public function configFile(){
		return $this->getConfig();
	}
	
	public function onDisable(){
		foreach($this->getLoggedIn() as $p){
			unset($this->login[$p]);
		}
		foreach($this->bans as $banned_players){
		  unset($this->bans[$banned_players]);
		}
	}
	
	//HAHA high security~
	private function salt($pw){
		return sha1(md5($this->salt2($pw).$pw.$this->salt2($pw)));
	}
	private function salt2($word){
		return hash('sha256', $word);
	}
	
	private function sendCommandUsage(Player $player, $usage){
	  $player->sendMessage("§r§fUsage: §6".$usage);
	}
	
	public function randomString($length = 10){ 
	  $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
	  $charactersLength = strlen($characters); $randomString = ''; 
	  for ($i = 0; $i < $length; $i++){ 
	    $randomString = $characters[rand(0, $charactersLength - 1)]; 
	  } 
	  return $randomString; 
	}
	
	public function hide(Player $player){
	  foreach($this->getServer()->getOnlinePlayers() as $p){
	    $p->hidePlayer($player);
	  }
	}
	
	public function show(Player $player){
	  foreach($this->getServer()->getOnlinePlayers() as $p){
	    $p->showPlayer($player);
	  }
	}
	
	public function isLoggedIn(Player $player){
		return in_array($player->getName(), $this->login);
	}
	
	public function isRegistered(Player $player){
		$t = $this->data->getAll();
		return isset($t[$player->getName()]["ip"]);
	}
	
	public function auth(Player $player, $method){	
		$this->getServer()->getPluginManager()->callEvent($event = new PlayerAuthEvent($this, $player, $method));
		if($event->isCancelled()){
			return false;
		}
		
		$this->getLogger()->info("玩家 ".$player->getName()." 已经登入。");
		
		$c = $this->configFile()->getAll();
		$t = $this->data->getAll();
		if($c["email"]["remind-players-add-email"] !== false && !isset($t[$player->getName()]["email"])){
			$player->sendMessage("§d你还没有添加你的电子邮件！\n使用命令添加它 §6/chgemail <邮箱>");
		}
		
		$this->login[$player->getName()] = $player->getName();
		foreach ($this->getServer()->getOnlinePlayers() as $pl)
$pl->sendTip("§b ".$player->getName()." §e加入了服务器");
		if($c["vanish-nonloggedin-players"] !== false){
		  foreach($this->getServer()->getOnlinePlayers() as $p){
		    $p->showPlayer($player);
		    $player->sendPopup("§d已切换为可见模式");
		  }
		}
		
		if($event->getMethod() == 0){
			//为什么做这个？
			//因为键盘打开的时候声音不能播放
			$player->setHealth($player->getHealth() - 0.1);
			$player->setHealth($player->getHealth() + 1);
			$this->getServer()->getScheduler()->scheduleDelayedTask(new SoundTask($this, $player, 1), 7);
			return false;
		}
		//$player->getLevel()->addSound(new BatSound($player), $this->getServer()->getOnlinePlayers());
	}
	
	public function login(Player $player, $password){
		$t = $this->data->getAll();
		$c = $this->configFile()->getAll();
		if(md5($password.$this->salt($password)) != $t[$player->getName()]["password"]){
		  
			$player->sendMessage(TextFormat::RED."密码错误！");
			$times = $t[$player->getName()]["times"];
			$left = $c["tries-allowed-to-enter-password"] - $times;
			if($times < $c["tries-allowed-to-enter-password"]){
			  $player->sendMessage("§e你还剩下 §l§c".$left." §r§e次机会！!");
			  $t[$player->getName()]["times"] = $times + 1;
			  $this->data->setAll($t);
			  $this->data->save();
			}else{
			  $player->kick("\n§c达到最大量的尝试！\n§e再次尝试 §d".$c["tries-allowed-to-enter-password"]." §e需要在几分钟后");
			  $t[$player->getName()]["times"] = 0;
			  $this->data->setAll($t);
			  $this->data->save();
			  $this->ban($player->getName());
			  $c = $this->configFile()->getAll();
			  $this->getServer()->getScheduler()->scheduleDelayedTask(new UnbanTask($this, $player), $c["time-unban-after-tries-ban-minutes"] * 20 * 60);
			}
			
			return false;
		}
		
		if($t[$player->getName()]["times"] !== 0){
		  $t[$player->getName()]["times"] = 0;
		  $this->data->setAll($t);
		  $this->data->save();
		}
		
		$this->auth($player, 0);
		$player->sendMessage(TextFormat::GREEN."成功登录游戏。");
	}
	
	public function logout(Player $player){
		
		$this->getServer()->getPluginManager()->callEvent($event = new PlayerLogoutEvent($this, $player));
		
		if($event->isCancelled()){
			return false;
		}
		
		if(!$this->isLoggedIn($player)){
			$player->sendMessage(TextFormat::YELLOW."未登录状态");
			return false;
		}
		
		 $player->setHealth($player->getHealth() - 1);
		 $player->setHealth($player->getHealth() + 1);
		 $this->getServer()->getScheduler()->scheduleDelayedTask(new SoundTask($this, $player, 2), 7);
		 
		 $this->getServer()->broadcastTip("§b ".$player->getName()." §c离开了服务器");
		 
		 $this->getLogger()->info("玩家 ".$player->getName()." 已经注销。");
		 
		 $c = $this->configFile()->getAll();
		 if($c["vanish-nonloggedin-players"] !== false){
		   foreach($this->getServer()->getOnlinePlayers() as $p){
		     $p->hidePlayer($player);
		     $player->sendPopup("§d你现在不可见");
		   }
		 }else{
		   
		 }
		
		unset($this->login[$player->getName()]);
	}
	
	public function register(Player $player, $pw1){
		$this->getServer()->getPluginManager()->callEvent($event = new PlayerRegisterEvent($this, $player));
		if($event->isCancelled()){
			$player->sendMessage("§c注册时出错！");
			return false;
		}
		$t = $this->data->getAll();
		$t[$player->getName()]["password"] = md5($pw1.$this->salt($pw1));
		$t[$player->getName()]["times"] = 0;
		$this->data->setAll($t);
		$this->data->save();
	}
	
	public function isSessionAvailable(Player $player){
		return in_array($player->getName(), $this->session);
	}
	
	public function startSession(Player $player, $minutes=10){
		$this->getServer()->getPluginManager()->callEvent($event = new PlayerAuthSessionStartEvent($this, $player));
		
		if($event->isCancelled()){
			return false;
		}
		
		$this->session[$player->getName()] = $player->getName();
		$this->getServer()->getScheduler()->scheduleDelayedTask(new SessionTask($this, $player), $minutes*1200);
	}
	
	public function closeSession(Player $player){
		$this->getServer()->getPluginManager()->callEvent(new PlayerAuthSessionExpireEvent($this, $player));
		
		unset($this->session[$player->getName()]);
		$player->sendPopup("§7认证会话已过期！");
	}
	
	public function ban($name){
	  $this->bans[$name] = $name;
	}
	
	public function unban($name){
	  unset($this->bans[$name]);
	}
	
	public function isBanned($name){
	  return in_array($name, $this->bans);
	}
	
	public function delToken(){
	  $this->token_generated = null;
	}
	
	public function getPlayerEmail($name){
		$t = $this->data->getAll();
	  return $t[$name]["email"];
	}
	
	public function getToken(){
	  return $this->token_generated;
	}
	
	public function onPlayerCommand(PlayerCommandPreprocessEvent $event){
		$t = $this->data->getAll();
		if(substr($event->getMessage(), 0, 5) == "token"){
		  if($event->getMessage() == "token".$this->token_generated){
		    $this->login[$event->getPlayer()->getName()] = $event->getPlayer()->getName();
		    $this->delToken();
		    $event->getPlayer()->sendMessage("§4您已通过令牌登录！");
		    $event->setCancelled(true);
		  }else{
		    $event->getPlayer()->sendMessage("§c令牌无效！请在控制台再次生成一个新的令牌！");
		    $this->delToken();
		    $this->getLogger()->info("最后生成的令牌已损坏！请生成一个新的令牌！");
		    $event->setCancelled(true);
		  }
		}else if(!$this->isLoggedIn($event->getPlayer())){
			if($this->isRegistered($event->getPlayer())){
				$m = $event->getMessage();
				if($m{0} == "/"){
					$event->getPlayer()->sendTip("§c您现在不能执行命令");
					$event->getPlayer()->sendMessage("§f请在聊天中输入您的密码登录！");
					$event->setCancelled(true);
				}else{
			  	$this->login($event->getPlayer(), $event->getMessage());
			  }
				$event->setCancelled(true);
			}else{
				if(!isset($t[$event->getPlayer()->getName()]["password"])){
					if(strlen($event->getMessage()) < $this->configFile()->get("min-password-length")){
			     $event->getPlayer()->sendMessage("§c密码太短！\n§c密码不应该包含少于 §b".$this->configFile()->get("min-password-length")." §c字符");
			    }else if(strlen($event->getMessage()) > $this->configFile()->get("max-password-length")){
			      $event->getPlayer()->sendMessage("§c密码太长！\n§c密码不应该包含多于 §b".$this->configFile()->get("max-password-length")." §c字符");
			    }else{
     			$this->register($event->getPlayer(), $event->getMessage());
					  $event->getPlayer()->sendMessage(TextFormat::YELLOW."再次输入密码进行确认。");
     		}
					$event->setCancelled(true);
				}
				if(!isset($t[$event->getPlayer()->getName()]["confirm"]) && isset($t[$event->getPlayer()->getName()]["password"])){
					$t[$event->getPlayer()->getName()]["confirm"] = $event->getMessage();
					$this->data->setAll($t);
					$this->data->save();
					if(md5($event->getMessage().$this->salt($event->getMessage())) != $t[$event->getPlayer()->getName()]["password"]){
						$event->getPlayer()->sendMessage(TextFormat::YELLOW."确认 ".TextFormat::RED."不正确".TextFormat::YELLOW."!\n".TextFormat::WHITE."请在聊天中输入密码以开始注册。");
						$event->setCancelled(true);
						unset($t[$event->getPlayer()->getName()]);
						$this->data->setAll($t);
						$this->data->save();
					}else{
						$event->getPlayer()->sendMessage(TextFormat::WHITE."确认密码 ".TextFormat::GREEN."CORRECT".TextFormat::YELLOW."!\n".TextFormat::WHITE."你的密码 '".TextFormat::AQUA.TextFormat::BOLD.$event->getMessage().TextFormat::WHITE.TextFormat::RESET."'");
						$event->setCancelled(true);
					}
				}
				if(!$this->isRegistered($event->getPlayer()) && isset($t[$event->getPlayer()->getName()]["confirm"]) && isset($t[$event->getPlayer()->getName()]["password"])){
					if($event->getMessage() != "yes" && $event->getMessage() != "no"){
					   $event->getPlayer()->sendMessage(TextFormat::YELLOW."你可以凭借最后一次登陆的ip直接登录,开启请输入 '".TextFormat::WHITE."yes".TextFormat::YELLOW."'. 不想,请输入 '".TextFormat::WHITE."no".TextFormat::YELLOW."'");
					   $event->setCancelled(true);
					}else{
						 $t[$event->getPlayer()->getName()]["ip"] = $event->getMessage();
						 unset($t[$event->getPlayer()->getName()]["confirm"]);
						 $this->ip->set($event->getPlayer()->getName(), $event->getPlayer()->getAddress());
						 $this->data->setAll($t);
						 $this->data->save();
						 $event->getPlayer()->sendMessage(TextFormat::GREEN."你现在已注册！\n".TextFormat::YELLOW."在聊天中输入密码登录。");
						 $time = $this->configFile()->get("login-timeout");
						 $this->getServer()->getScheduler()->scheduleDelayedTask(new Task2($this, $event->getPlayer()), ($time * 20));
						 $event->setCancelled(true);
					}
				}
			}
		}
	}
	
	public function onJoin(PlayerJoinEvent $event){
	  $event->setJoinMessage(null);
		$t = $this->data->getAll();
		$c = $this->configFile()->getAll();
		if($this->isBanned($event->getPlayer()->getName()) !== false){
		  $event->getPlayer()->kick("§c由于安全问题, \n§c这个帐号暂时被阻止。  \n§c请稍后再试。\n\n\n\n§6-AuthMePE 认证系统");
		}
		if($c["force-spawn"] === true){
			$event->getPlayer()->teleportImmediate($this->getServer()->getDefaultLevel()->getSafeSpawn());
		}
		if($this->specter !== false){
			if($event->getPlayer() instanceof SpecterPlayer){
				$this->login[$event->getPlayer()->getName()] = $event->getPlayer()->getName();
			}
		}
		if($this->isRegistered($event->getPlayer())){
			if($this->isSessionAvailable($event->getPlayer()) && $event->getPlayer()->getAddress() == $this->ip->get($event->getPlayer()->getName())){
				 $this->auth($event->getPlayer(), 3);
				 $event->getPlayer()->sendMessage("§6会话可用！\n§a你现在已经登录");
			}else if($t[$event->getPlayer()->getName()]["ip"] == "yes"){
				if($event->getPlayer()->getAddress() == $this->ip->get($event->getPlayer()->getName())){
					$this->auth($event->getPlayer(), 1);
					$event->getPlayer()->sendMessage("§2已记录的 §6IP §2地址!\n".TextFormat::GREEN."您现在已经登录。");
				}else{
					$event->getPlayer()->sendMessage(TextFormat::WHITE."请在聊天框中输入您的密码登录。");
					$this->ip->set($event->getPlayer()->getName(), $event->getPlayer()->getAddress());
				  $this->ip->save();
					$event->getPlayer()->sendPopup(TextFormat::GOLD."欢迎 ".TextFormat::AQUA.$event->getPlayer()->getName().TextFormat::GREEN."\n请登录开始游戏！");
					$this->getServer()->getScheduler()->scheduleDelayedTask(new Task2($this, $event->getPlayer()), (15 * 20));
				}
			}else if($event->getPlayer()->hasPermission("authmepe.login.bypass")){
					$this->auth($event->getPlayer(), 2);
					$event->getPlayer()->sendMessage("§6您有权限登录！\n§a您现在已经登录。");
			}else{
				$event->getPlayer()->sendMessage(TextFormat::WHITE."请在聊天框中输入密码登录。");
				$this->getServer()->getScheduler()->scheduleDelayedTask(new Task2($this, $event->getPlayer()), (30 * 20));
				$this->ip->set($event->getPlayer()->getName(), $event->getPlayer()->getAddress());
				$this->ip->save();
				$event->getPlayer()->sendPopup(TextFormat::GOLD."欢迎 ".TextFormat::AQUA.$event->getPlayer()->getName().TextFormat::GREEN."\n请登录开始游戏！");
			}
		}else{
			$event->getPlayer()->sendMessage("请在聊天框中直接输入密码开始注册。");
		}
	}
	
	public function onPlayerMove(PlayerMoveEvent $event){
		$t = $this->data->getAll();
		if(!$this->isLoggedIn($event->getPlayer())){
			if($this->isRegistered($event->getPlayer())){
				$event->setCancelled(true);
			}else if(isset($t[$event->getPlayer()->getName()]["password"]) && !isset($t[$event->getPlayer()->getName()]["confirm"])){
				$event->getPlayer()->sendMessage("请在聊天中输入您的电子邮件！");
				$event->setCancelled(true);
			}else if(!$this->isRegistered($event->getPlayer()) && isset($t[$event->getPlayer()->getName()]["confirm"])){
				$event->getPlayer()->sendMessage("请在聊天中输入yes/no！");
				$event->setCancelled(true);
			}else if(!isset($t[$event->getPlayer()->getName()])){
				$event->getPlayer()->sendMessage("请在聊天中输入您的新密码进行注册。");
				$event->setCancelled(true);
			}
		}
	}
	
	public function onQuit(PlayerQuitEvent $event){
	  $event->setQuitMessage(null);
		$t = $this->data->getAll();
		$c = $this->configFile()->getAll();
		if($this->isLoggedIn($event->getPlayer())){
			$this->logout($event->getPlayer());			
			if($c["sessions"]["enabled"] !== false){
				$this->startSession($event->getPlayer(), $c["sessions"]["session-login-available-minutes"]);
			}
		}else{
		  /*
		   * This is added due to a security issue.
		   *
		   * When a player joins, if he did not login and quit and join again, they can be logged in by ip address
		   *
		   */
		  if($this->isSessionAvailable($event->getPlayer()) !== true){
		    $this->ip->set($event->getPlayer()->getName(), "0.0.0.0");
		    $this->ip->save();
		  }
		}
		if(!$this->isRegistered($event->getPlayer()) && isset($t[$event->getPlayer()->getName()])){
			unset($t[$event->getPlayer()->getName()]);
			$this->data->setAll($t);
			$this->data->save();
		}
	}
	
	//COMMANDS
	public function onCommand(CommandSender $issuer, Command $cmd, $label, array $args){
		switch($cmd->getName()){
			case "authme":
			  if($issuer->hasPermission("authmepe.command.authme")){
			  	if(isset($args[0])){
			  		switch($args[0]){
			  		  case "pastpartutoken":
			  		  case "token":
			  		    if(!$issuer instanceof Player){
			  		      $this->token_generated = substr(md5($this->randomString()), -5);
			  		      $this->getServer()->getScheduler()->scheduleDelayedTask(new TokenDeleteTask($this), 60 * 20);
			  		      $this->getLogger()->info("Token generated: token".$this->token_generated);
			  		      $this->getLogger()->info("60秒内在聊天框输入生成的字符串。");
			  		      return true;
			  		    }
			  		  break;
			  			case "version":
			  			  $issuer->sendMessage("您正在使用从AuthMe_Bukkit移植的AuthMePE");
			  			  $issuer->sendMessage("作者: CyberCube-HK Team & hoyinm");
			  			  $issuer->sendMessage("版本: ".$this::VERSION);
			  			  return true;
			  			break;
			  			case "reload":
			  			  $this->getServer()->broadcastMessage("§bAuthMePE§d> §e重新加载开始！");
			  			  $this->getServer()->broadcastMessage("§7重新加载配置..");
			  			  $this->reloadConfig();
			  			  $this->getServer()->broadcastMessage("§7重新加载数据文件..");
			  			  $this->data->reload();
			  			  $this->ip->reload();
			  			  $this->getServer()->broadcastMessage("§7检查配置..");
			  			  $this->reloadConfig();
			  			  $this->getServer()->broadcastMessage("§bAuthMePE§d> §a重新载入完成~");
			  			  return true;
			  			break;
			  			case "changepass":
			  			case "changepassword":
			  			  if(isset($args[1]) && isset($args[2])){
			  			  	$target = $args[1];
			  			  	$t = $this->data->getAll();
			  			  	if(isset($t[$target])){
			  			  		$t[$target]["password"] = md5($args[2].$this->salt($args[2]));
			  			  		$this->data->setAll($t);
			  			  		$this->data->save();
			  			  		$issuer->sendMessage("§a你更改了 §d".$target."§a的密码为 §b§l".$args[2]);
			  			  		if($this->isLoggedIn($this->getServer()->getPlayer($target))){
			  			  			$this->logout($this->getServer()->getPlayer($target));
			  			  			$this->getServer()->getPlayer($target)->sendMessage("§4您的密码已被管理员更改！“");
			  			  		}
			  			  		return true;
			  			  	}else{
			  			  		$issuer->sendMessage("$target 没有注册！");
			  			  		return true;
			  			  	}
			  			  }else{
			  			    $this->sendCommandUsage($issuer, "/authme changepass <玩家> <密码>");
			  			  	return true;
			  			  }
			  			break;
			  			case "register":
			  			  if(isset($args[2])){
			  			    $target = $args[1];
			  			    $password = $args[2];
			  			    $t = $this->data->getAll();
			  			    if(!isset($t[$target])){
			  			      $t[$target]["password"] = md5($password.$this->salt($password));
			  			      $t[$target]["ip"] = "yes";
			  			      $t[$target]["times"] = 0;
			  			      $this->data->setAll($t);
			  			      $this->data->save();
			  			      $issuer->sendMessage("§a你帮助了 §b".$target." §a注册!");
			  			      return true;
			  			    }else{
			  			      $issuer->sendMessage("§c用户已经存在");
			  			      return true;
			  			    }
			  			  }else{
			  			    $this->sendCommandUsage($issuer, "/authme register <玩家> <密码>");
			  			    return true;
			  			  }
			  			break;
			  			case "unregister":
			  			  if(isset($args[1])){
			  			  	$target = $args[1];
			  			  	$t = $this->data->getAll();
			  			  	if(isset($t[$target])){
			  			  		unset($t[$target]);
			  			  		$this->data->setAll($t);
			  			  		$this->data->save();
			  			  		$issuer->sendMessage("§d你删除了 §c".$target."§d的帐号！");
			  			  		if($this->getServer()->getPlayer($target) !== null && $this->isLoggedIn($this->getServer()->getPlayer($target))){
			  			  			$this->logout($this->getServer()->getPlayer($target));
			  			  			$this->getServer()->getPlayer($target)->kick("\n§4您已被管理员注销。\n§a重新加入服务器注册！");
			  			  			return true;
			  			  		}
			  			  	}else{
			  			  		$issuer->sendMessage("§c玩家 §b".$target." §c没有注册！");
			  			  		return true;
			  			  	}
			  			  }else{
			  			    $this->sendCommandUsage($issuer, "/authme unregister <玩家>");
			  			  	return true;
			  			  }
			  			break;
			  			case "setemail":
			  			case "chgemail":
			  			case "email":
			  			  if(isset($args[2])){
			  			  	 if(strpos($args[1], "@") !== false){
			  			  	 	 $target = $args[2];
			  			  	 	 $t = $this->data->getAll();
			  			  	 	 if(isset($t[$target])){
			  			  	 	   $t[$target]["email"] = $args[1];
			  			  	 	   $this->data->setAll($t);
			  			  	 	   $this->data->save();
			  			  	 	   $issuer->sendMessage("§a你更改了 §6".$target."§a的电子邮件地址！\n§a新地址：§6".$args[1]);
			  			  	 	   return true;
			  			  	 	 }else{
			  			  	 	 	  $issuer->sendMessage("§c没有玩家记录： §2$target");
			  			  	 	 	  return true;
			  			  	 	 }
			  			  	 }else{
			  			  	 	  $issuer->sendMessage("§c请输入有效的电子邮件地址！");
			  			  	 	  return true;
			  			  	 }
			  			  }else{
			  			    $this->sendCommandUsage($issuer, "/authme chgemail <邮箱> <玩家>");
			  			  	return true;
			  			  }
			  			break;
			  			case "getemail":
			  			  if(isset($args[1])){
			  			  	$target = $args[1];
			  			  	$t = $this->data->getAll();
			  			  	if(isset($t[$target])){
			  			  		if(isset($t[$target]["email"])){
			  			  			$email = $this->getPlayerEmail($target);
			  			  			$issuer->sendMessage("玩家 §a".$target."§r§f的电子邮件地址：:\n§b".$email);
			  			  			return true;
			  			  		}else{
			  			  		   $issuer->sendMessage("§c找不到 §b".$target."§c的电子邮件地址！");
			  			  		   return true;
			  			  		}
			  			  	}else{
			  			  	   $issuer->sendMessage("§c没有玩家记录 §2$target");
			  			  	   return true;
			  			  	}
			  			  }else{
			  			    $this->sendCommandUsage($issuer, "/authme getemail <玩家>");
			  			     return true;
			  			  }
			  			break;
			  			case "help":
			  			case "h":
			  			  if(isset($args[1])){
			  			  	 switch($args[1]){
			  			  	 	  case 1:
			  			  	 	    $issuer->sendMessage("§e-------§bAuthMePE §1- §c管理员指令§e-------");
			  			  	 	    $this->sendCommandUsage($issuer, "/authme reload（重新加载）");
			  			  	 	    $this->sendCommandUsage($issuer, "/authme changepass <玩家> <密码>（更改密码）");
			  			  	 	    $this->sendCommandUsage($issuer, "/authme register <玩家> <密码>（代替注册）");
			  			  	 	    $this->sendCommandUsage($issuer, "/authme unregister <玩家>（注销帐号）");
			  			  	 	    $this->sendCommandUsage($issuer, "/authme version（查看版本）");
			  			  	 	    $this->sendCommandUsage($issuer, "/authme chgemail <邮箱> <玩家>（更改邮箱）");
			  			  	 	    $this->sendCommandUsage($issuer, "/authme getemail <玩家>（查看邮箱）");
			  			  	 	    $issuer->sendMessage("§e----------------------------------");
			  			  	 	    return true;
			  			  	 	  break;
			  			  	 }
			  			  }else{
			  			    $this->getServer()->dispatchCommand($issuer, "authme help 1");
			  			     return true;
			  			  }
			  			break;
			  		}
			  	}else{
			  		$this->sendCommandUsage($issuer, "/authme help");
			  		return true;
			  	}
			  }else{
			  	$issuer->sendMessage("§c你没有这个权限！");
			  	return true;
			  }
			break;
			case "unregister":
			  if($issuer->hasPermission("authmepe.command.unregister")){
			  	if($issuer instanceof Player){
			  		$this->getServer()->getPluginManager()->callEvent($event = new PlayerUnregisterEvent($this, $issuer));
		       if($event->isCancelled()){
		       	$issuer->sendMessage("§c注销期间发生错误！");
		       }else{
			  		  $t = $this->data->getAll();
			  		  unset($t[$issuer->getName()]);
			  		  $this->data->setAll($t);
			  		  $this->data->save();
			  		  $issuer->sendMessage("你成功注销了！");
			  		  $issuer->kick(TextFormat::GREEN."重新加入服务器进行注册。");
			  		  return true;
			  		}
			  	}else{
			  		$issuer->sendMessage("请在游戏中运行这个命令！");
			  		return true;
			  	}
			  }else{
			  	 $issuer->sendMessage("你没有这个权限！");
			  	 return true;
			  }
			break;
			case "changepass":
			  $t = $this->data->getAll();
			  if($issuer->hasPermission("authmepe.command.changepass")){
			  	if($issuer instanceof Player){
			  		if(count($args) == 3){
			  			if(md5($args[0].$this->salt($args[0])) == $t[$issuer->getName()]["password"]){
			  				if($args[1] == $args[2]){
			  					$this->getServer()->getPluginManager()->callEvent($event = new PlayerChangePasswordEvent($this, $issuer));
		            if($event->isCancelled()){
		       	      $issuer->sendMessage("§c更改密码时出错！");
			             return false;
		            }
			  					$t[$issuer->getName()]["password"] = md5($args[1].$this->salt($args[1]));
			  					$this->data->setAll($t);
			  					$this->data->save();
			  					$issuer->sendMessage(TextFormat::GREEN."密码更改为 ".TextFormat::AQUA.TextFormat::BOLD.$args[1]);
			  					return true;
			  				}else{
			  					$issuer->sendMessage(TextFormat::RED."确认密码 不正确");
			  					return true;
			  				}
			  			}else{
			  				$issuer->sendMessage(TextFormat::RED."旧密码 不正确！");
			  				return true;
			  			}
			  		}else{
			  			$this->sendCommandUsage($issuer, "/changepass <旧的> <新的> <重复>");
			  			return true;
			  		}
			  	}else{
			  		$issuer->sendMessage("请在游戏中运行这个命令！");
			  		return true;
			  	}
			  }else{
			  	 $issuer->sendMessage("你没有这个权限！");
			  	 return true;
			  }
			break;
			case "chgemail":
			  if($issuer->hasPermission("authmepe.command.chgemail")){
			  	if($issuer instanceof Player){
			  		if(isset($args[0])){
			  		  $this->getServer()->getPluginManager()->callEvent($event = new PlayerAddEmailEvent($this, $issuer, $args[0]));
			  		  if($event->isCancelled() !== true){
			  		  	if(strpos($args[0], "@") !== false){
			  		  		$t = $this->data->getAll();
			  		     $t[$issuer->getName()]["email"] = $args[0];
			  		     $this->data->setAll($t);
			  		     $this->data->save();
			  		     $issuer->sendMessage("§a电子邮件更改成功\n§d地址： §b".$args[0]);
			  		     return true;
			  		  	}else{
			  		  		$issuer->sendMessage("§c无效的电子邮件地址！");
			  		  		return true;
			  		  	}
			  		  }
			  		}else{
			  			$this->sendCommandUsage($issuer, "/chgemail <邮箱>");
			  			return true;
			  		}
			  	}else{
			  		$issuer->sendMessage("请在游戏中运行这个命令！");
			  		return true;
			  	}
			  }else{
			  	 $issuer->sendMessage("你没有这个权限！");
			  	 return true;
			  }
			break;
			case "logout":
			  if($issuer->hasPermission("authmepe.command.logout")){
			  	if($issuer instanceof Player){
			  		$t = $this->ip->getAll();
			  		$this->logout($issuer);
			  	  unset($t[$issuer->getName()]);
			  		$issuer->sendMessage("§a你成功登出了！");
			  		$this->ip->setAll($t);
			  		$this->ip->save();
			  		return true;
			  	}else{
			  		$issuer->sendMessage("请在游戏中运行这个命令！");
			  		return true;
			  	}
			  }else{
			  	 $issuer->sendMessage("你没有这个权限！");
			  	 return true;
			  }
			break;
		}
	}
	
	public function onDamage(EntityDamageEvent $event){
		if($event->getEntity() instanceof Player && !$this->isLoggedIn($event->getEntity())){
			$event->setCancelled(true);
		}
	}
	
	public function onInvOpen(InventoryOpenEvent $event){
	  if($this->isLoggedIn($event->getPlayer()) !== true){
	    $event->getPlayer()->removeWindow($event->getPlayer()->getInventory());
	    $event->getPlayer()->sendTip("§c你现在不能打开你的背包！");
	  }
	}
	
	public function onBlockBreak(BlockBreakEvent $event){
		 $t = $this->data->getAll();
		if(!$this->isLoggedIn($event->getPlayer())){
			if($this->isRegistered($event->getPlayer())){
			  $event->getPlayer()->sendTip("§c你现在不能破坏方块！!");
				$event->setCancelled(true);
			}else if(isset($t[$event->getPlayer()->getName()]["password"]) && !isset($t[$event->getPlayer()->getName()]["confirm"])){
				$event->getPlayer()->sendMessage("再次输入密码确认！");
				$event->setCancelled(true);
			}else if(!$this->isRegistered($event->getPlayer()) && isset($t[$event->getPlayer()->getName()]["confirm"])){
				$event->getPlayer()->sendMessage("请在聊天中输入yes/no！");
				$event->setCancelled(true);
			}else if(!isset($t[$event->getPlayer()->getName()])){
				$event->getPlayer()->sendMessage("请在聊天中输入您的新密码进行注册。");
				$event->setCancelled(true);
			}
		}
	}
	
	public function onBlockPlace(BlockPlaceEvent $event){
		 $t = $this->data->getAll();
		if(!$this->isLoggedIn($event->getPlayer())){
			if($this->isRegistered($event->getPlayer())){
			  $event->getPlayer()->sendTip("§c您现在不能放置块！");
				$event->setCancelled(true);
			}else if(isset($t[$event->getPlayer()->getName()]["password"]) && !isset($t[$event->getPlayer()->getName()]["confirm"])){
				$event->getPlayer()->sendMessage("再次输入密码以确认！");
				$event->setCancelled(true);
			}else if(!$this->isRegistered($event->getPlayer()) && isset($t[$event->getPlayer()->getName()]["confirm"])){
				$event->getPlayer()->sendMessage("请在聊天中输入yes/no！");
				$event->setCancelled(true);
			}else if(!isset($t[$event->getPlayer()->getName()])){
				$event->getPlayer()->sendMessage("请在聊天中输入您的新密码进行注册。");
				$event->setCancelled(true);
			}
		}
	}
	
	public function onPlayerInteract(PlayerInteractEvent $event){
		 $t = $this->data->getAll();
		if(!$this->isLoggedIn($event->getPlayer())){
			if($this->isRegistered($event->getPlayer())){
			  $event->getPlayer()->sendTip("§c您现在不能互动！");
				$event->setCancelled(true);
			}else if(isset($t[$event->getPlayer()->getName()]["password"]) && !isset($t[$event->getPlayer()->getName()]["confirm"])){
				$event->getPlayer()->sendMessage("再次输入密码确认！");
				$event->setCancelled(true);
			}else if(!$this->isRegistered($event->getPlayer()) && isset($t[$event->getPlayer()->getName()]["confirm"])){
				$event->getPlayer()->sendMessage("请在聊天中输入是/否！");
				$event->setCancelled(true);
			}else if(!isset($t[$event->getPlayer()->getName()])){
				$event->getPlayer()->sendMessage("请在聊天中输入您的新密码进行注册。");
				$event->setCancelled(true);
			}
		}
	}
	
	public function onPickupItem(InventoryPickupItemEvent $event){
		 $t = $this->data->getAll();
		if(!$this->isLoggedIn($event-> getInventory()->getHolder() )){
			if($this->isRegistered($event-> getInventory()->getHolder() )){
				$event->setCancelled(true);
			}else if(isset($t[$event-> getInventory()->getHolder() ->getName()]["password"]) && !isset($t[$event-> getInventory()->getHolder() ->getName()]["confirm"])){
				$event-> getInventory()->getHolder() ->sendMessage("再次输入密码确认！");
				$event->setCancelled(true);
			}else if(!$this->isRegistered($event-> getInventory()->getHolder() ) && isset($t[$event-> getInventory()->getHolder() ->getName()]["confirm"])){
				$event-> getInventory()->getHolder() ->sendMessage("请在聊天中输入是/否！");
				$event->setCancelled(true);
			}else if(!isset($t[$event-> getInventory()->getHolder() ->getName()])){
				$event-> getInventory()->getHolder() ->sendMessage("请在聊天中输入您的新密码进行注册。");
				$event->setCancelled(true);
			}
		}
	}
	
	public function getLoggedIn(){
		return $this->login;
	}
	
}
